import axios from "axios";
import {getToken} from "@/utils/TokenUtil";
import {ElMessage} from "element-plus";
import sysConfig from "@/config/index"

const devURL="http://localhost:82/"
const proURL="http://localhost:80/app/youlibin_typewriting/phpscript"
const reloadCodes = [401, 1011007, 1011008]
const errorCodeMap =new Map([
    [400,'发出的请求有错误，服务器没有进行新建或修改数据的操作。'],
    [401,'请先登录'],
    [415,"参数错误"],
    [403, '禁止访问'],
    [404, '未知服务'],
    [1,"未知错误"]
])

let request = axios.create({
   baseURL:devURL,
   timeout:sysConfig.TIMEOUT,
   timeoutErrorMessage:"服务器超时"
});
export interface Response{
    code:number,
    data:any,
    msg:string
}
request.interceptors.request.use(
    config => {
        const token = getToken()
        if(token){
            config.headers[sysConfig.TOKEN_HEADER_NAME] = sysConfig.TOKEN_PREFIX + token
        }

        // 此处添加Loading
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

request.interceptors.response.use(
    (response) => {
        const code = response.data.code
        if(code === 500){
            ElMessage({
                type:"error",
                message:response.data.msg
            })
        }else if(code !== 200){
            ElMessage({
                type:"error",
                message:errorCodeMap.get(code) || errorCodeMap.get(1)
            })
        }
        return response.data
    },
    error => {

        // 处理异常情况，根据项目实际情况处理或不处理
        if (error && error.response) {
            error.message = errorCodeMap.get(error.response.status)
        } else {
            // 超时处理
            error.message = errorCodeMap.get(500);
        }
        return Promise.resolve(error.response);
    }
);
// 适用于php
// function handleUrl(baseUrl:string,url:string):string{
//     url=url.replace("/","")
//     return baseUrl+'.php?m='+url
// }


// java
function handleUrl(baseUrl:string,url:string):string{
    return baseUrl+url
}
export function get(baseUrl:string,url:string,args?:any){
    return request.get(handleUrl(baseUrl,url), {
        params: args
    })
}

export function post(baseUrl:string,url:string,args?:any){
    return request.post(handleUrl(baseUrl,url), args)
}


export default request